package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApUnLikeBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApUnLikeBehaviorService;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class ApUnLikeBehaviorServiceImpl extends ServiceImpl<ApUnLikeBehaviorMapper, ApUnlikesBehavior> implements ApUnLikeBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(AppThreadLocalUtils.getUser().getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(502,"行为实体不存在");
        }
        //查询ap_unlikes_behavior表中的数据
        ApUnlikesBehavior unlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()).eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));
        if (unlikesBehavior==null){
            ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setType(dto.getType());
            save(apUnlikesBehavior);
        }else {
            unlikesBehavior.setType(dto.getType());
            updateById(unlikesBehavior);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
